<template>
  <n-drawer v-model:show="isDrawer" :width="width" :placement="placement">
    <n-drawer-content :title="title" closable>
      <n-form
        :model="formParams"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="100"
      >
        <n-form-item label="菜单名称" path="menuName">
          <n-input placeholder="请输入菜单名称" v-model:value="formParams.menuName" />
        </n-form-item>
        <n-form-item label="菜单键" path="menuKey">
          <n-input placeholder="请输入菜单键" v-model:value="formParams.menuKey" />
        </n-form-item>
        <n-form-item label="父菜单" path="parentId">
          <n-tree-select
            :options="options"
            key-field="id"
            label-field="menuName"
            :default-expanded-keys="[formParams.parentId]"
            :default-value="formParams.parentId"
            v-model:value="formParams.parentId"
          />
        </n-form-item>
        <n-form-item label="排序" path="sort">
          <n-input-number
            v-model:value="formParams.sort"
            placeholder="菜单序号"
            :min="1"
          />
        </n-form-item>
      </n-form>

      <template #footer>
        <n-space>
          <n-button type="primary" :loading="subLoading" @click="formSubmit">提交</n-button>
          <n-button @click="handleReset">重置</n-button>
        </n-space>
      </template>
    </n-drawer-content>
  </n-drawer>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, toRefs } from 'vue';
import { useMessage } from 'naive-ui';
import { addMenu } from '@/api/authority/menu';

const rules = {
  menuName: {
    required: true,
    message: '请输入菜单名称',
    trigger: 'blur',
  },
  menuKey: {
    required: true,
    message: '请输入菜单键',
    trigger: 'blur',
  },
  parentId: {
    required: true,
    validator (rule, value: string) {
      if (!value) {
        return new Error('请选择菜单关联父菜单')
      }
      return true
    },
    trigger: 'blur',
  },
  sort: {
    required: true,
    validator (rule, value: string) {
      console.log(value)
      if (!value) {
        return new Error('请输入菜单序号')
      } else if (!/^\d*$/.test(value)) {
        return new Error('序号应该为整数')
      }
      return true
    },
    trigger: 'blur',
  },
};
export default defineComponent({
  name: 'CreateDrawer',
  components: {},
  props: {
    title: {
      type: String,
      default: '添加顶级菜单',
    },
    width: {
      type: Number,
      default: 450,
    },
    parentId: {
      type: Number,
      default: -1,
    },
  },
  setup(props, emit) {
    const message = useMessage();
    const formRef: any = ref(null);
    const { parentId } = toRefs(props)
    const defaultValueRef = () => ({
      menuName: '',
      menuKey: '',
      parentId: parentId,
      sort: 1,
    });

    const state = reactive({
      isDrawer: false,
      subLoading: false,
      formParams: defaultValueRef(),
      placement: 'right' as const,
      alertText:
        '该功能主要实时预览各种布局效果，更多完整配置在 projectSetting.ts 中设置，建议在生产环境关闭该布局预览功能。',
      options: [],
    });

    const initOptions = async (treeMenuList) => {
      // @ts-ignore
      state.options = [{
        id: -1,
        menuName: '顶级菜单',
        menuKey: 'menu',
        parentId: -1,
        children: treeMenuList
      }]
    }

    function openDrawer() {
      state.isDrawer = true;
    }

    function closeDrawer() {
      state.isDrawer = false;
    }

    function formSubmit() {
      formRef.value.validate(async (errors) => {
        state.subLoading = true;
        if (!errors) {
          await addMenu({
            menuName: state.formParams.menuName,
            menuKey: state.formParams.menuKey,
            parentId: state.formParams.parentId,
            sort: state.formParams.sort,
          })
          handleReset();
          closeDrawer();
          emit.emit('handlerInit')
        } else {
          message.error('请填写完整信息');
        }
        state.subLoading = false;
      });
    }

    function handleReset() {
      formRef.value.restoreValidation();
      state.formParams = Object.assign(state.formParams, defaultValueRef());
    }

    return {
      ...toRefs(state),
      formRef,
      rules,
      formSubmit,
      handleReset,
      openDrawer,
      closeDrawer,
      initOptions
    };
  },
});
</script>
